package models

import (
	"gitee.com/xiangxiaoc/elevator/funcs"
	"log"
	"time"
)

type Elevator struct {
	Name          string
	CurrentFloor  Floor
	RunningStatus string
	Destination   Floor
	DoorStatus    string
}

func (e Elevator) LogElevator() {
	log.Printf("当前楼层：%v，电梯%v", e.CurrentFloor, e.RunningStatus)
}

func (e *Elevator) rise() {
	e.RunningStatus = "上行"
	e.LogElevator()
	time.Sleep(1 * time.Second)
	e.CurrentFloor++
}

func (e *Elevator) descend() {
	e.RunningStatus = "下行"
	e.LogElevator()
	time.Sleep(1 * time.Second)
	e.CurrentFloor--
}

func (e *Elevator) pauseWaitPassengerInAndOut() {
	e.RunningStatus = "停止"
	e.openDoor()
	for i := 0; i < 3; i++ {
		log.Printf("等待 %v 秒", 3-i)
		time.Sleep(1 * time.Second)
	}

	e.closeDoor()
}

func (e *Elevator) goToDestFloor(dest Floor, system *ElevatorSystem) {
	e.Destination = dest
	log.Printf("开始前往：%v 层", e.Destination)
	time.Sleep(1 * time.Second)
	for e.Destination != e.CurrentFloor {
		switch {
		case funcs.IsInArray(e.CurrentFloor, system.ElevatorDestList) == true:
			log.Printf("检测到 %v 层有人按电梯，命令电梯暂停前往 %v 层，并开门接乘客", e.CurrentFloor, e.Destination)
			time.Sleep(1 * time.Second)
			system.ElevatorDestList = funcs.DeleteElements(system.ElevatorDestList, e.CurrentFloor)
			log.Printf("移除楼层队列中剩余的 %v 层", e.CurrentFloor)
			e.pauseWaitPassengerInAndOut()
		case e.Destination > e.CurrentFloor:
			e.rise()
		case e.Destination < e.CurrentFloor:
			e.descend()
		default:
			log.Println("其他情况，不做任何操作")
		}
	}
	log.Printf("当前楼层：%v，电梯已到达目的地", e.CurrentFloor)
	time.Sleep(1 * time.Second)
	e.pauseWaitPassengerInAndOut()
}

func (e *Elevator) openDoor() {
	log.Printf("当前楼层：%v，电梯开门", e.CurrentFloor)
	time.Sleep(2 * time.Second)
	e.DoorStatus = "已开门"
}

func (e *Elevator) closeDoor() {
	log.Printf("当前楼层：%v，电梯关门", e.CurrentFloor)
	time.Sleep(2 * time.Second)
	e.DoorStatus = "已关门"
}
